import Vue from "vue";
import VueRouter from "vue-router";
import login from "@/views/login/login.vue";
import layout from "@/views/layout/layout.vue";
import chart from "@/views/layout/chart/chart.vue";
import user from "@/views/layout/user/user.vue";
import question from "@/views/layout/question/question.vue";
import business from "@/views/layout/business/business.vue";
import subject from "@/views/layout/subject/subject.vue";

import Nprogress from "nprogress";
import "nprogress/nprogress.css";

Vue.use(VueRouter);
// 实例化
const router = new VueRouter({
  routes: [
    {
      path: "/",
      redirect: "/login",
    },
    {
      path: "/login",
      component: login,
      meta: {
        title: "登录页面",
        roles: ["超级管理员", "管理员", "老师", "学生"],
      },
    },
    {
      path: "/layout",
      component: layout,
      redirect: "/layout/subject",
      children: [
        {
          path: "/layout/chart",
          component: chart,
          meta: {
            title: "数据概览",
            roles: ["超级管理员", "管理员", "老师"],
            icon: "el-icon-pie-chart",
          },
        },
        {
          path: "/layout/user",
          component: user,
          meta: {
            title: "用户列表",
            roles: ["超级管理员", "管理员"],
            icon: "el-icon-user",
          },
        },
        {
          path: "/layout/question",
          component: question,
          meta: {
            title: "题库列表",
            roles: ["超级管理员", "管理员", "老师"],
            icon: "el-icon-edit-outline",
          },
        },
        {
          path: "/layout/business",
          component: business,
          meta: {
            title: "企业列表",
            roles: ["超级管理员", "管理员", "老师"],
            icon: "el-icon-office-building",
          },
        },
        {
          path: "/layout/subject",
          component: subject,
          meta: {
            title: "学科列表",
            roles: ["超级管理员", "管理员", "老师", "学生"],
            icon: "el-icon-notebook-2",
          },
        },
      ],
    },
    {
      path: "*",
      redirect: "/login",
    },
  ],
});
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

import store from "@/store/index.js";
import { Message } from "element-ui";
import { removeLocal } from "@/utils/local.js";

// 路由前置守卫
router.beforeEach((to, from, next) => {
  console.log("前置to", to);
  console.log("前置from", from);
  // 这一个就是点击的时候加载条
  Nprogress.start();
  // 当前要to的路由的路由元中是否包含当前登录人角色  如果包含  next()
  if (to.meta.roles.includes(store.state.role)) {
    next();
  } else {
    // 如果不包含
    // 就提示一下
    Message.error("您无权访问该页面");
    // 删除token
    removeLocal("token");
    // 去到登录页
    next("/login");
  }
});

// 路由后置守卫
router.afterEach((to, from) => {
  console.log(from);
  Nprogress.done();
  document.getElementById("title").innerText = to.meta.title;
});

export default router;
